var util = require("../../utils/util.js");
var api = require('../../config/api.js');


//获取应用实例
var app = getApp()
var startPoint
Page({
  data: {
    isHidden: false,
    imageList: [],
    navbar_bgcolor: wx.getStorageSync('navbar_bgcolor'),
    dialogShow: false,
    buttons: [{ text: '取消' }, { text: '确定' }],
    carModel: '',
    schoolList: [],
    coachsList: [],
    classTypeList: [],
    newsList:[],
    buttonClicked: false,

    //按钮位置参数
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: '',
    windowWidth: '',
    //角标显示数字
    corner_data:0,
  },

  onLoad: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var scollHeight = res.screenHeight - 90;
        that.setData({
          scollHeight: scollHeight
        });
        that.getIndexData();
        that.CheckEval();
      }
    });
    //var user = wx.getStorageSync("userInfo");
    //console.log("当前登陆的用户信息是：：："+JSON.stringify(user));
    //var token = wx.getStorageSync("token");
    //console.log("当前登陆的用户信息是：tokentoken：："+JSON.stringify(token));



    //定义角标数字
    this.setData({
      corner_data:3
    })
    // 获取购物车控件适配参数
    var that =this;
    wx.getSystemInfo({
      success: function (res) {
        //console.log(res);
        // 屏幕宽度、高度
        //console.log('height=' + res.windowHeight);
        //console.log('width=' + res.windowWidth);
        // 高度,宽度 单位为px
        that.setData({
          windowHeight:  res.windowHeight,
          windowWidth:  res.windowWidth,
          buttonTop:res.windowHeight*0.82,//这里定义按钮的初始位置
          buttonLeft:res.windowWidth*0.80,//这里定义按钮的初始位置
        })
      }
    })
  },
  
  // 去stu表取合同的签署状态判断是否认证完成
 state:function () {
   var that = this;
   var userid = wx.getStorageSync("userid");
   console.log(userid)
   util.request(api.getsigningStatus, {userid:userid}).then(function (res) {
     console.log(res)
     if(res.data === "0"){
      that.again();
     }
   })  
 },
  //重新授权
 again:function(){
  var that = this;
  console.log("重新获取签署链接")
  var auth = null;
  var userid = wx.getStorageSync("userid");
  util.request(api.againHtUrl, {userid:userid}).then(function (res) {
   if(res.errno === 0){
      //跳转认证页面
      wx.navigateTo({
        url: '/pages/signupV3/authurl'
      })
   }else{
    wx.showModal({
      title: '提示',
      content: '获取签约链接异常，请联系管理员!',
      showCancel: false
    })
   }
 })  
 },
  openPopup() {
    // console.log("yushuaixm-----------------------------------");
    const _this = this;
    // 获取用户的当前设置，判断是否点击了“总是保持以上，不在询问”
    wx.getSetting({
      withSubscriptions: true, // 是否获取用户订阅消息的订阅状态，默认false不返回
      success(res) {
        console.log('res.authSetting', res.authSetting)
        if (res.authSetting['scope.subscribeMessage']) {
          console.log('用户点击了“总是保持以上，不再询问”')
        } else {
          console.log('用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息')
          //因为没有选择总是保持，所以需要调起授权弹窗再次授权
          _this.authorizationBtn();
        }
      }
    })
  },
// 授权
authorizationBtn() {
  wx.requestSubscribeMessage({
    tmplIds: ['Owjudd8RKemLOUsyy4vnSP2gntu121zJUx4th9gnugw', 'Owjudd8RKemLOUsyy4vnSNTPFPAI5_Ak4C7TYIvT7AU'],
    success(res) {
      console.log('授权成功')
    }
  })
},


  onPullDownRefresh: function () {
    
  },
  onReady: function() {
    //console.log("调用到了这里onReady");

  },
  checkWq:function(){
    //获取用户的ID
    var hasLogin = wx.getStorageSync("app.globalData.hasLogin");
    if(hasLogin){//进行判断是否授权
      var userid = wx.getStorageSync("userid");
      //console.log("yushuaixm:::::userid::::"+userid);
      //根据用户的ID，进行判断是否存在评价
      util.request(api.checkUserWq, {uid:userid}).then(function (res) {
        var status = res.data.status;
        if(status == '0'){
          var id = res.data.msg;
          wx.navigateTo({
            url: '../wq/index?id='+id
          })
        }
      })
      //进行评价页面跳转
      /*wx.navigateTo({
        url: '../wq/index'
      })*/
    } 
  },
  onShow: function () {
    var hasLogin = wx.getStorageSync("app.globalData.hasLogin");
    //console.log("个人加载中....V2V::::"+hasLogin);
    if(hasLogin){
      let userInfo = wx.getStorageSync('userInfo');
      //console.log("All+++"+JSON.stringify(userInfo));
      var userid = wx.getStorageSync("userid");
      console.log("获取微信用户的数据库的基本信息：：userid::::"+userid);
      if(userid != ''){
        util.request(api.checkLoginByWeixin, {"uid":userid,key:api.key},"POST").then(function (res) {
           console.log(JSON.stringify(res));
          if(res.errno === 402){
            wx.showModal({
              title: '错误',
              content:'不被允许的请求',
              showCancel: false
            })
            return;
          }
          if(res.data.nickname == '微信用户'){
            wx.navigateTo({
              url: "/pages/auth/login/login"
            });
          }
          /*if(res.errno != '404'){
            wx.setStorageSync("user",res.data);
            wx.setStorageSync("userid",res.data.id);
          }*/
        })
      }

    //绑定的用户，进行获取是否需要进行评价-驾校教练
    this.checkWq();
    }
    
    

  },
  getIndexData: function () {
    var that = this;
    util.request(api.IndexList).then(function (res) {
      if (res.errno === 0) {
        //console.log("news:::::"+JSON.stringify(res.data.bannerList));
        that.setData({
          classTypeList: res.data.classTypeList,
          schoolList:res.data.deptList,
          coachsList:res.data.coachList,
          newsList:res.data.newsList,
          imageList:res.data.bannerList
        });
      }
    });
  },
  CheckEval: function () {
    var that = this;
    var userid = wx.getStorageSync("userid");
    //console.log("VVVV1:::::"+userid);
    if(userid == ''){
      return;
    }
    
    this.state();
    return;
    /*
    util.request(api.CheckEval, {uid:userid,key:api.key}).then(function (res) {
      if (res.errno === 0) {
        if(res.data==true){
            wx.showModal({
              title: '提示',
              content: '您的全部科目已学完，请您对驾校予以评价',
              showCancel:false,
              success (res) {
                if (res.confirm) {
                  that.toEval();
                }
              }
            })

        }
      }else if(res.errno === 402){
        wx.showModal({
          title: '错误',
          content:'不被允许的请求',
          showCancel: false
        })
    }
    });
    */
  },

  toBillBoard: function () {
    wx.navigateTo({
      url: '/pages/billboard/list/list',
    })
  },
  toCoachBillBoard: function () {
    wx.navigateTo({
      url: '/pages/coachBillboard/list/list',
    })
  },

  openConfirm: function () {
    this.setData({
      dialogShow: true
    })
  },
  tapDialogButton(e) {
    //console.log(e.detail.index);//0为取消  1为确认
    this.setData({
      dialogShow: false
    })
    return;
    var index = e.detail.index;
    if (index == 1) {//确认
      if (this.data.carModel == '') {
        util.showErrorToast('请选择车型');
        return;
      }
      var hasLogin = wx.getStorageSync("app.globalData.hasLogin");
      //console.log("VVVV1-2");
      if (!hasLogin) {
        wx.navigateTo({
          url: "/pages/auth/login/login"
        });
        return;
      }
      this.setData({
        dialogShow: false
      })
      util.redirect('/pages/signupV3/info?carModel=' + this.data.carModel);
      // wx.navigateTo({
      //   url: '/pages/signupV3/info?carModel='+this.data.carModel
      // })
      return
    }
    this.setData({
      dialogShow: false,
      carModel: ''
    })

  },
  toSchoolByTrainToDetail:function(e){
    var param = e.currentTarget.dataset;
    var id = param["id"];
    var model = param["model"];

    wx.navigateTo({
      // url: '../school/show/detail?model='+model+'&id=' + id + '&from=index'
      url: '../school/detail/detail?model='+model+'&id=' + id + '&from=index'
    })

    
  },
  toSchoolDetail: function (e) {
    var param = e.currentTarget.dataset;
    var id = param["id"];
    wx.navigateTo({
      // url: '../school/show/detail?id=' + id + '&from=index'
      url: '../school/detail/detail?id=' + id + '&from=index'
    })
  },
  toCoachDetail: function (e) {
    var param = e.currentTarget.dataset;
    var id = param["id"];
    wx.navigateTo({
      url: '../coach/detail/detail?id=' + id
    })
  },
  toClassMore: function () {
    wx.navigateTo({
      url: '/pages/classType/index'
    })
  },
  toCoachList: function () {
    wx.switchTab({
      url: '/pages/coach/list/list',
    })
    wx.navigateTo({
      url: '/pages/coach/list/list',
    })
  },
  toSignUp: function () {
    util.buttonClicked(this);
    var hasLogin = wx.getStorageSync("app.globalData.hasLogin");
    //console.log("VVVV1-3");
    if (!hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    } else {
      //5s须知
      wx.navigateTo({
        //url: '/pages/signupV3/selectCarModel'
        url:'/pages/clause/index'
      })
    }
  },
  toTrain: function () {
    var hasLogin = wx.getStorageSync("app.globalData.hasLogin");
    //console.log("VVVV1-4");
    if (!hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    }
    /*wx.showLoading({
      title: '加载中...'
    })*/
    var userid = wx.getStorageSync("userid");
    //console.log("VVVV1-5");
    if(userid == ''){
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    }
    util.request(api.AppointmentMySchoolInfo, {uid:userid,key:api.key}).then(function (res) {
      //wx.hideLoading();
      if (res.errno === 0) {//须根据当前学员step状态判断是否可进行预约
        var data = res.data;
        wx.hideLoading();
        wx.navigateTo({
          url: '/pages/train/clause/index?userName=' + data.userName+'&phone='+data.phone,
        })
      } else if(res.errno === 402){
        wx.showModal({
          title: '错误',
          content:'不被允许的请求',
          showCancel: false
        })
      }else if (res.errno === 507) {
        //wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '您还未报名...',//报名进行中... 0912
          showCancel: false
        })
      } else if (res.errno === 508) {
       // wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '请完成评价后，继续进行预约',
          confirmText: '去评价',
          confirmColor: '#4169E1',
          success(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/train/record/index?type=0',
              })
            }
          }
        })
      }
    });
  },
  toExam: function () {
    wx.navigateTo({
      url: '/pages/exam/index'
    })
  },
  toNews_5:function(){
    wx.navigateTo({
      url: '/pages/news/list/list?type=5',
    })
  },
  toNews_6:function(){
    wx.navigateTo({
      url: '/pages/news/list/list?type=6',
    })
  },
  toNewsMoreZcfg:function(){
    wx.navigateTo({
      url: '/pages/news/list/list?type=2',
    })
  },
  toNewsMore:function(){
    wx.navigateTo({
      url: '/pages/news/list/list?type=1',
    })
  },
  toNewsRead:function(e){
    var param = e.currentTarget.dataset;
    var id = param["id"];
    // console.log(id);
    wx.navigateTo({
      url: '../news/read/read?id=' + id
    })
  },
  toSchool: function () {
    wx.navigateTo({
      url: '/pages/school/list/list'
    })
  },
  toMonitor:function(){
    wx.navigateTo({
      url: '/pages/monitor/index',
    })
  },
  toEval: function () {
    wx.showModal({
      title: '提示',
      content: '开发中...',
      showCancel: false
    })
    return;
    var hasLogin = wx.getStorageSync("app.globalData.hasLogin");
    //console.log("VVVV1-6");
    if (!hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    }

    /*wx.navigateTo({
      url: '/pages/eval/school/add?schoolId=3268&schoolName=大学城驾校',
    })*/


    var userid = wx.getStorageSync("userid");
    //console.log("VVVV1-7");
    if(userid == ''){
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    }
    util.request(api.LearnTimeMySchoolInfo, {uid:userid}).then(function (res) {
      if (res.errno === 0) {
        var data = res.data;
        wx.navigateTo({
          //url: '/pages/eval/add?schoolId=' + data.schoolId + '&schoolName=' + data.schoolName + '&userName=' + data.userName,
          url: '/pages/eval/school/add?schoolId=' + data.schoolId + '&schoolName=' + data.schoolName + '&userName=' + data.userName
        })
      } else if (res.errno === 507) {
        wx.showModal({
          title: '提示',
          content: 'res.errmsg',
          showCancel: false
        })
        //util.showInfoToast(res.errmsg);
      } else if (res.errno === 509) {
        wx.showModal({
          title: '提示',
          content: res.errmsg,
          showCancel: false
        })
      }

      wx.hideLoading();
    });
  },
  toJLZS: function () {
    var hasLogin = wx.getStorageSync("app.globalData.hasLogin");
    //console.log("VVVV1-8");
    if (!hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    }

    var userid = wx.getStorageSync("userid");
    //console.log("VVVV1-9");
    if(userid == ''){
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
      return;
    }
    util.request(api.getCoachSign, {uid:userid,key:api.key}).then(function (res) {
      console.log(res);
      if (res.errno === 0) {
        if (res.data == '0') {//未注册
          wx.showModal({
            title: '提示',
            content: '您的账号暂未认证，请提交资料审核！',
            confirmText: '去认证',
            confirmColor: '#4169E1',
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/jlzs/apply/index',
                })
              }
            }
          })
        } else if (res.data == '1') {//
          wx.showModal({
            title: '提示',
            content: '教练身份认证审核中...',
            showCancel:false
          })
        } else if (res.data == '2') {//审核通过
          wx.navigateTo({
            url: '/pages/jlzs/index/index',
          });
        }else if(res.data == '3'){
          wx.showModal({
            title: '提示',
            content: '审核未通过，是否重新进行认证？',
            success (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/jlzs/apply/index',
                })
              }
            }
          })
        }
      }else if(res.errno === 402){
        wx.showModal({
          title: '错误',
          content:'不被允许的请求',
          showCancel: false
        })
    }else{
        wx.showModal({
          title: '提示',
          content: '您还未报名...',
          showCancel: false
        })
      }
      wx.hideLoading();
    });
  },
  toDMV: function () {
    wx.navigateTo({
      url: '/pages/dmv/list/list',
    })
  },
  toExamSite: function () {
    wx.navigateTo({
      url: '/pages/examSite/index',
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var me = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '日照交通交警市场监管',
      path: '/pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  select: function (event) {
    var type = event.currentTarget.dataset.type;
    var that = this;
    that.setData({
      carModel: type
    });
  },
  toXykh:function(){
    wx.navigateTo({
      url: '/pages/xykh/main',
    })
  },
  toyfx: function(){
    wx.downloadFile({
      url: 'https://www.rzjspxxh.com/yfx.pdf',
      success: function (res) {
        if (res.statusCode === 200) { 
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            fileType:'pdf',
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        }
      }
    })
  },
  toDriveBook: function () {
    wx.navigateTo({
      url: '/pages/news/xxyd/xxyd',
    })

    /*wx.downloadFile({
      url: 'https://www.rzjspxxh.com/point.pdf',
      success: function (res) {
        if (res.statusCode === 200) { 
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            fileType:'pdf',
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        }
      }
    })*/
    // wx.navigateTo({
    //   url: '/pages/driveBook/index',
    // })
  },
  toSchoolList:function(){
    //console.log("xxxyyy");
    /*wx.switchTab({
      url: '/pages/school/list/list',
    })*/
    wx.navigateTo({
      url: '/pages/school/list/slist',
    })
  },




  //可拖动悬浮按钮点击事件
  btn_Suspension_click:function(){
    //这里是点击购物车之后将要执行的操作
    wx.showToast({
      title: '点击成功',
      icon:'success',
      duration:1000
    })
  },
  //以下是按钮拖动事件
  buttonStart: function (e) {
    startPoint = e.touches[0]//获取拖动开始点
  },
  buttonMove: function (e) {
    var endPoint = e.touches[e.touches.length - 1]//获取拖动结束点
    //计算在X轴上拖动的距离和在Y轴上拖动的距离
    var translateX = endPoint.clientX - startPoint.clientX
    var translateY = endPoint.clientY - startPoint.clientY
    startPoint = endPoint//重置开始位置
    var buttonTop = this.data.buttonTop + translateY
    var buttonLeft = this.data.buttonLeft + translateX
    //判断是移动否超出屏幕
    if (buttonLeft+50 >= this.data.windowWidth){
      buttonLeft = this.data.windowWidth-50;
    }
    if (buttonLeft<=0){
      buttonLeft=0;
    }
    if (buttonTop<=0){
      buttonTop=0
    }
    if (buttonTop + 50 >= this.data.windowHeight){
      buttonTop = this.data.windowHeight-50;
    }
    this.setData({
      buttonTop: buttonTop,
      buttonLeft: buttonLeft
    })
  },
  buttonEnd: function (e) {
  }
})
